/*
 * @Author: 抱著羊啃 1437670973@qq.com
 * @Date: 2025-04-18 00:28:59
 * @LastEditors: 抱着羊啃 1437670973@qq.com
 * @LastEditTime: 2025-04-23 16:29:40
 * @FilePath: \demo1\src\main\java\org\example\demo1\servlets\ManagePage\insertUserServlet.java
 * @Description: 這是默認設定,請設定`customMade`, 打開koroFileHeader查看配置 進行設定: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package org.example.demo1.servlets.ManagePage;

import com.google.gson.Gson;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.example.demo1.DAO.UserDao;
import org.example.demo1.utils.MybatisUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/API/user/insert")
public class insertUserServlet extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        // 移除角色相关代码
        // String role_id = req.getParameter("role_id");
        String status = req.getParameter("status");

        Map<String, Object> result = new HashMap<>();
        SqlSession sqlSession = null;

        // 檢查必填參數
        if(username == null || username.isEmpty() || password == null || password.isEmpty()) {
            result.put("code", 400);
            result.put("msg", "用戶名和密碼不能為空");
            resp.getWriter().print(new Gson().toJson(result));
            return;
        }

        sqlSession = MybatisUtils.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        try {
            
            // 檢查用戶名是否已存在
            if(userDao.getUserInformation(username) != null) {
                result.put("code", 400);
                result.put("msg", "用戶名已存在");
            } else {
                // 使用insertUserManager方法插入新用戶
                Map<String, Object> params = new HashMap<>();
                params.put("username", username);
                params.put("password", password);

                if (status != null && !status.isEmpty()) {
                    params.put("status", Integer.parseInt(status));
                } else {
                    // 默認狀態為正常
                    params.put("status", 1);
                }
                  
                if(email != null && !email.isEmpty()) {
                    params.put("email", email);
                }
                if(phone != null && !phone.isEmpty()) {
                    params.put("phone", phone);
                }
                
                // 插入用户基本信息
                userDao.insertUserManager(params);
                
                // 获取新插入用户的ID
                Integer userId = userDao.getUserInformation(username).getUser_id();
                
                // 在user_role表中添加默认角色关联(角色ID为1)
                org.example.demo1.DAO.UserRoleDao userRoleDao = sqlSession.getMapper(org.example.demo1.DAO.UserRoleDao.class);
                userRoleDao.insertUserRole(userId, 1); // 直接传入user_id和role_id参数
                
                sqlSession.commit();
                
                result.put("code", 200);
                result.put("msg", "用戶添加成功");
            }
        } catch (Exception e) {
            if(sqlSession != null) {
                sqlSession.rollback();
            }
            result.put("code", 500);
            result.put("msg", "系統錯誤: " + e.getMessage());
            e.printStackTrace();
        } finally {
            if(sqlSession != null) {
                sqlSession.close();
            }
        }
        
        // 返回JSON響應
        PrintWriter out = resp.getWriter();
        out.print(new Gson().toJson(result));
        out.flush();
    }
}
